package com.example.micro_property_springboot.config;


import com.example.micro_property_springboot.exce.BizException;
import com.example.micro_property_springboot.pojo.VO.Result;
import io.swagger.v3.oas.annotations.Hidden;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
@Hidden
public class GlobalExceptionAdvice {
    // 针对特定的异常处理
    @ExceptionHandler(BizException.class)
    public Result<?> handleBizException(BizException e){
        return Result.error(e.getCode(),e.getMessage());
    }
    // 处理所有异常
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e){
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleException(MethodArgumentNotValidException e ){
        Map<String,String> map = new HashMap();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        }
        return Result.error(5000,"数据校验失败",map);
    }
}